package com.example.excel.alibaba;

import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelExportServiceImpl implements ExcelExportService{
    //在springboot文件(application.properties)中配置模板所在的位置，例如
    //excel.template=E:/SpringToolSuiteForEclipseWorkSpace/PrivateApplication/EasyExcel/src/main/resources/1.xlsx
    @Value("../src/resources/templates/fish.xlsx")
    private String templateFileName;


    @Override
    public void excelExport(HttpServletResponse response) throws IOException {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        System.out.println(templateFileName);
        // 方案1 根据对象填充
        String fileName = "simpleFill" + System.currentTimeMillis() + ".xlsx";
        //String fileName = "simpleFill" + System.currentTimeMillis() + ".xlsx";
        // 这里 会填充到第一个sheet， 然后文件流会自动关闭
        List<FillData> l = new ArrayList<>();
        for(Integer i = 0; i < 50; i++){
            FillData fillData = new FillData();
            fillData.setName("张三" + i+"号");
            fillData.setChinese(120.0+i);
            fillData.setEnglish(141.0+i);
            fillData.setMath(119.0+i);
            fillData.setNumber(fillData.getChinese()+fillData.getEnglish()+fillData.getMath());
            l.add(fillData);
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition","attachment;filename="+new String(fileName.getBytes(),"iso-8859-1"));
        EasyExcel.write(response.getOutputStream()).inMemory(true).registerWriteHandler(new WaterMarkHandler("我是水印"))
                .withTemplate(templateFileName).sheet().doFill(l);
//        EasyExcel.write(response.getOutputStream(), FillData.class).withTemplate(templateFileName)
//                .inMemory(true) // 注意，此项配置不能少
//                .registerWriteHandler(new WaterMarkHandler("我是水印"))
//                .sheet("模板")
//                .doWrite(l);
    }
}

